package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 让springmvc直接将当前登录用户注入到请求映射方法的参数中去
 *
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;



    //该解析器支持解析哪一种类型的参数 UserInfo
    //如果返回false:不支持解析,不执行resolveArgument方法
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType()== UserInfo.class
                && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    //上面方法返回true时执行
    //将上面支持类型转化为具体实例对象,注入请求映射方法的形参上
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        HttpServletRequest req = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse resp = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

        String token = CookieUtil.getToken(req);
        UserInfo user = userInfoRedisService.getUserByToken(token);



        return user;
    }
}
